<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="author" content="100200cs"/>
    <title>编辑项目</title>

    <link href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcss.com/weui/1.1.2/style/weui.min.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-weui/1.2.0/css/jquery-weui.min.css">
    <script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/jquery-weui.min.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/swiper.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/city-picker.min.js"></script>



    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>自定义输入框获取焦点</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <style>
        * {margin: 0; padding: 0; border: 0;}
        body {
            position: absolute;
            width: 100%;
            height: 100%;
        }
        #geoPage, #markPage {
            position: relative;
        }
    </style>

    <style type="text/css">
        .weui-uploader__file{
            border-radius: 6px;
            position: relative;
        }
        .my_smallbox{
            position: absolute;top:0;right: 0;height:20px;width:20px;background-color: rgba(47,47,47,0.5);
            border-top-right-radius: 6px;
            border-bottom-left-radius: 4px;
            text-align: center;
            line-height: 20px;
            color: #ffffff;
            font-size: 16px;
        }
        .my_bottombox{
            position: absolute;bottom:0;left:0;right: 0;height:20px;background-color: rgba(47,47,47,0.5);
            border-bottom-right-radius: 6px;
            border-bottom-left-radius: 6px;
            text-align: center;
            line-height: 20px;
            color: #ffffff;
            font-size: 12px;

        }
        .for_gallery{
            position: absolute;bottom:10px;left:10px;right: 10px;
            width: 60%;height:40px;background-color: rgba(47,47,266,0.5);
            z-index: 20;
            opacity: 0;

        }
        .for_gallery2{
            position: absolute;bottom:10px;left:10px;top: 10px;
            width: 40px;height:70%;background-color: rgba(47,47,266,0.5);
            z-index: 20;
            opacity: 0;

        }
        .divdiv{
            width: 100%;height:fit-content;text-align:center;display: block;
            opacity: 1;
        }
        .divdiv img{
            max-width: 50%;
        }
    </style>
</head>
<body style="background-color: #f8f8f8">
<div>


</div>

<script>
    var ioio=null;
    var html;
    var img_urls='';
    function rand(){
        var r= Math.floor( ( Math.random() * (100000000-10000000+1 ) + 10000000 ));
        return(""+new Date().getTime()+'_'+r);
    };
    var submitting=false;
    function submit_now() {
        if(submitting){
            $.toptip('请不要重复提交','forbidden');
        }
        submitting=true;

        img_urls=new Array();
        html=''+$('#test').html();
        if($('#test').text().length<10){
            $.toast('至少10个字！','forbidden');
            return;
        }


        function up_img(div_imgs,cur) {
            if (cur >= div_imgs.length) {
                console.log('new html');
                console.log(html);

                $.ajax({
                    url: 'upload_html',//url
                    data: {html: html,imgs:img_urls,title:$('#test').text(),loc:$('#locating').text()},
                    type: 'POST',// 'POST' or 'GET'
                    dataType: 'json',//'json' or 'text' or 'html'
                    timeOut:10000,
                    error:function(XMLHttpRequest, textStatus, errorThrown){
                        console.error('ajax error:'+errorThrown);
                        $.toast("网络超时<br>稍后重试", "cancel");
                        submitting=false;
                    },
                    success: function (data) {
                        if (data['success']) {
                           console.log('all seccess');
                            $.toast("发布成功<br>即将返回首页", function() {
                                window.location.href="/";
                            });

                        }else{
                            console.log('dddd',JSON.stringify(data,null,4));
                            // $('#dubug').html(data);
                        }
                    }
                });

                return;
             }
            var imgsrc=$(div_imgs[cur]).children('img').attr('src');
            var img_id=$(div_imgs[cur]).attr('id').replace('_img','');

            $('#'+img_id).children("div.my_bottombox").children('span').text('上传中...');
            // console.log(imgsrc);
            $.ajax({
                url: 'upload',//url
                data: {img64: imgsrc},
                type: 'POST',// 'POST' or 'GET'
                dataType: 'json',//'json' or 'text' or 'html'
                timeOut:10000,
                error:function(XMLHttpRequest, textStatus, errorThrown){
                    console.error('ajax error:'+errorThrown);
                    console.log('time out');
                    $.toast("网络超时<br>稍后重试", "cancel");
                    submitting=false;
                },
                success: function (data) {
                    console.log('ajax: ' + data['file_name']);
                    if (data['file_name'] && data['file_name'] != 1 && data['file_name'] != 2) {
                        $('#'+img_id).children("div.my_bottombox").children('span').text('上传成功');
                        html=html.replace('#'+img_id+'_img',data['file_name']);
                        console.log('88');
                        img_urls.push(data['file_name']);
                        up_img(div_imgs,cur+1);

                    }else{
                        $.toast("网络超时<br>稍后重试", "cancel");
                        console.log('dddd',JSON.stringify(data,null,4));
                    }
                }
            });
        }

        var div_imgs=$('.divdiv');
        var li_files=$('li');
        for(var p=0;p<li_files.length;p++){
            var img_id=$(li_files[p]).attr('id')+'_img';
            if($('#'+img_id).length > 0){
                $(li_files[p]).children("div.my_bottombox").children('span').text('等待上传');
                $(li_files[p]).children("div.my_smallbox").remove();
                $(li_files[p]).fadeTo('fast',1);
                var img_src=''+$('#'+img_id).children('img').attr('src');
                html=html.replace(img_src,'#'+img_id);

            }else{
                $(li_files[p]).remove();
            }
        }

        console.log('html');
        console.log(html);
        up_img(div_imgs,0);



    }

    var animate=function (div) {

        div.fadeTo('fast',0.5);
        div.fadeTo('fast',1);
        div.fadeTo('fast',0.5);
        div.fadeTo('fast',1);

    }
    var insert=function(thiz){

        var url=""+$(thiz).css("backgroundImage").replace('url(','').replace(')','').replace('\"','').replace('\"','');
        ioio=thiz;
        if($(thiz).children("div.my_bottombox").children('span').text()!='点击插入'){
            console.log('已使用');
            // $.toptip('操作成功', 'success');
            // $.toptip('操作失败', 'error');
            $.toptip('图片已使用', 'warning');
            return;
        }

        var height_1=$('#scroll_div').scrollHeight();
        // console.log(thiz);
        document.getElementById('test').focus();
        var img_id=$(thiz).attr("id")+"_img";
        insertHtmlAtCaret("<br> <div id=\"" +img_id+
            "\" class='divdiv' contenteditable='false' ><img " +
            "src=\""+url+"\" /></div><div><br></div>");
        $(thiz).children("div.my_bottombox").children('span').text('已使用');
        $(thiz).fadeTo('fast',0.5);
        var height_2=$('#scroll_div').scrollHeight();

        $('#scroll_div').scrollTop($('#scroll_div').scrollTop()+height_2-height_1);

        animate($('#'+img_id));

    }

</script>

<div class="weui-cells__title">请输入要发布的内容</div>
<div class="weui-cells" >
    <div id="scroll_div" class="weui-cell" style="overflow-y: scroll">
<div contenteditable="true" class="weui-textarea" style="height: 400px;max-height: 600px;" id="test">

</div>
<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>

<script type="text/javascript">
    var cursorPos=0;
    function insertHtmlAtCaret(html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);
                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }

        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    }
</script>
    </div>
    <div id="text_num" class="weui-textarea-counter"><span>0</span>/500</div>
</div>
<div class="weui-gallery" id="gallery" style="opacity: 1; display: none;">
    <span class="weui-gallery__img" id="galleryImg" style="background-image:url(#)"></span>
    <div class="weui-gallery__opr">
        <a href="javascript:" class="weui-gallery__del">
            <i class="weui-icon-delete weui-icon_gallery-delete"></i>
        </a>
    </div>
</div>

<div class="weui-cells weui-cells_form">
    <div class="weui-cell">
        <div class="weui-cell__bd">
            <div class="weui-uploader">
                <div class="weui-uploader__hd">
                    <p class="weui-uploader__title">添加图片</p>
                    <div id="img_num" class="weui-uploader__info">0/8</div>
                </div>
                <div class="weui-uploader__bd">
                    <ul class="weui-uploader__files" id="uploaderFiles">

                    </ul>
                    <div class="weui-uploader__input-box">
                        <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="multiple">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd"><label style="width:50px" class="weui-label">定位</label></div>
        <div class="weui-cell__bd">
            <span id='locating'  class="weui-input">正在定位...</span>
        </div>
        <div style="font-size: 20px;margin-left: 5px;" onclick="$('#mapPagePicker').fadeIn('fast')">
            <i class="fa fa-map-marker"></i>
        </div>
    </div>
</div>

<div class="weui-btn-area">
    <a href="javascript:submit_now();" class="weui-btn weui-btn_primary">立即提交</a>
</div>
<div id='dubug'><div  style="height: 20px;"></div></div>

<script type="text/javascript" class="uploader js_show">
    var img_num=0;
    var char_num=0;
    var options = {timeout: 8000};
    var geolocation = new qq.maps.Geolocation("5MHBZ-H6G3U-EODVN-2QY3E-R2ZLQ-XTBJM", "myapp");

    function showPosition(position) {
        $("#locating").text(""+position["province"]+position["city"]+position["addr"]);
        console.log(JSON.stringify(position, null, 4));
    };

    function showErr() {
        $("#locating").val("定位失败！");
    };

    geolocation.getLocation(showPosition, showErr, options);

    function compress(img, width, height, ratio) {
        var canvas, ctx, img64;

        var originWidth = img.width;
        var originHeight = img.height;
        // 最大尺寸限制
        var maxWidth = width, maxHeight = height;
        // 目标尺寸
        var targetWidth = originWidth, targetHeight = originHeight;
        // 图片尺寸超过限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
        }

        canvas = document.createElement('canvas');
        canvas.width = targetWidth;
        canvas.height = targetHeight;

        ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, targetWidth, targetHeight);
        ctx.drawImage(img, 0, 0, targetWidth, targetHeight);

        img64 = canvas.toDataURL("image/jpeg", ratio);

        return img64;
    }


    function check_img(){
        var files=$('li');
        for(var i=0;i<files.length;i++){
            var u=files[i];
            var img_id=$(u).attr('id')+'_img';
            if($('#'+img_id).length <= 0){
                if($(u).children("div.my_bottombox").children('span').text()=='已使用') {
                    $(u).children("div.my_bottombox").children('span').text('点击插入');
                    $(u).fadeTo('fast',1);
                }
            }
        }
    }

    var t1 = window.setInterval("check_img()",500);

    $(function(){
        var tmpl = '<li id=\"' +"[rand]"+
            '\" class="weui-uploader__file" > ' +
            '   <div class="my_smallbox"><i class="fa fa-close fa-th"></i></div>\n' +
            '  <input type="button" class="for_gallery"><input type="button" class="for_gallery2"><div class="my_bottombox"><span>正在压缩</span></div></li>',
            $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles")
        ;
        $uploaderInput.on('click',function () {
            if(img_num==8){
                $.toast("最多8张图片！",'forbidden');

            }
        })
        $uploaderInput.on("change", function(e){
            if(img_num==8)
                return;

            var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
            for (var i = 0, len = files.length; i < len; ++i) {
                var file = files[i];
                console.log("file  "+Math.ceil(file.size/1024)+'kB');

                if (url) {
                    src = url.createObjectURL(file);
                    console.log(''+src);
                } else {
                    src = e.target.result;
                    console.log('else: '+src);
                }

                $uploaderFiles.append($(tmpl.replace('[rand]',rand())));

                var img_tmp= new Image();
                img_tmp.onload = function () {
                    var img64 = compress(this, 900, 1600, 0.8);
                    // document.getElementById("test").src = img64;
                    console.log('img64; '+Math.ceil(img64.length/1024)+'kb');

                    var lili=$('li');
                    for(var io=0;io<lili.length;io++){
                        if($(lili[io]).css('background-image')=='none'){
                            $(lili[io]).css('background-image','url(#url#)'.replace('#url#', img64));
                            $(lili[io]).children("div.my_bottombox").children('span').text('点击插入');
                            return;
                        }
                    }
                };
                // 文件base64化，以便获知图片原始尺寸
                img_tmp.src = src;

                img_num+=1;
                $("#img_num").html(""+img_num+"/8");
                if(img_num==8)
                    return;
            }
        });
        $uploaderFiles.on("click", ".for_gallery", function(){
            console.log("for_gallery onclick");
            // $galleryImg.attr("style", this.parentNode.getAttribute("style"));
            // $gallery.fadeIn(100);
            insert(this.parentNode);
            console.log(this);
        });

        $("#test").on("input", function(e){
            $("#text_num").html(""+$(this).text().length+"/500");

            if($(this).text().length>500){
                $.toptip('最多输入500字', 'warning');
                e.preventDefault();
            }
        });

        $("#test").on("keypress", function(e){
            $("#text_num").html(""+$(this).text().length+"/500");
            if($(this).text().length>500){
                $.toptip('最多输入500字', 'warning');
                e.preventDefault();
            }
        });


        $uploaderFiles.on("click", ".for_gallery2", function(){
            console.log("for_gallery2 onclick");
            insert(this.parentNode);
        });

        $uploaderFiles.on("click", ".my_smallbox", function(){
            console.log("my_smallbox onclick");
            var thiz=this;
            $.confirm({
                title: '删除图片',
                text: '此操作也会删除插入的相同图片，确认删除？',
                onOK: function () {

                    var u=$(thiz).parent();
                    var img_id=$(u).attr('id')+'_img';
                    if($('#'+img_id).length > 0){
                        $('#'+img_id).remove();
                    }

                    $(thiz).parent().remove();
                    img_num-=1;
                    $("#img_num").text(""+img_num+"/8");

                },
                onCancel: function () {
                }
            });


        });

        $gallery.on("click", function(){
            console.log('$gallery onclick');
            $gallery.fadeOut(100);
        });
    });



</script>



<iframe id="mapPagePicker" width="100%" height="100%" frameborder=0 style="display:none;z-index: 2000;position: fixed;top:0;left: 0;right: 0"
        src="http://apis.map.qq.com/tools/locpicker?search=1&type=1&key=5MHBZ-H6G3U-EODVN-2QY3E-R2ZLQ-XTBJM&referer=myapp">
</iframe>

<script>
    var lll;
    window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        lll=loc;
        // console.log('location', loc);
        if (loc) {
            console.log(999);
            if (loc.module == "locationPicker"){
                console.log('location', loc.poiaddress);
                $("#locating").text(loc.poiaddress);
                $("#mapPagePicker").fadeOut('fast');
            }
            ;
        };
    }, false);

</script>

</body>

</html>